<template>
	<view class="warp">
		<!-- #ifdef APP-PLUS -->
		<statusBar></statusBar>
		<!-- #endif -->
		<!-- 顶部导航 -->
		<u-navbar @rightClick="rightClick" :autoBack="true">
		</u-navbar>
		<!-- banner -->
		<unicloud-db ref="bannerdb" v-slot:default="{data, loading, error, options}" collection="opendb-banner"
			field="_id,bannerfile,open_url,title" @load="onqueryload">
			<!-- 当无banner数据时显示占位图 -->
			<image v-if="!(loading||data.length)" class="banner-image" src="/static/uni-center/headers.png"
				mode="aspectFill" :draggable="false" />

			<swiper v-else class="swiper-box" @change="changeSwiper" :current="current" indicator-dots>
				<swiper-item v-for="(item, index) in data" :key="item._id">
					<view class="swiper-item" @click="clickBannerItem(item)">
						<image class="banner-image" :src="item.bannerfile.url" mode="aspectFill" :draggable="false" />
					</view>
				</swiper-item>
			</swiper>
		</unicloud-db>

		<!-- 帖子列表 --> <!-- 若使用:page-size="10"而不定义this.getNews()，则只会尝试渲染查到的前10条数据 -->
		<unicloud-db ref='udb' v-slot:default="{data, pagination, hasMore, loading, error, options}"
			:collection="colList" @error="onqueryerror">
			<!-- 基于 uni-list 的页面布局 field="user_id.nickname"-->
			<uni-list class="uni-list" :border="false" :style="{height:listHight}">
				<!-- 作用于app端nvue页面的下拉加载 -->
				<!-- #ifdef APP-NVUE -->
				<refreshBox @refresh="refresh" :loading="loading" />
				<!-- #endif -->

				<!-- 列表渲染 -->
				<!-- 因colList中用where筛选帖子类别，而联表查询为left outer join方式， -->
				<!-- 需要v-if判断来自PostCategories表的字段是否为空来判断是否是当前类别的帖子 -->
				<uni-list-item v-for="(item, index) in data" 
					v-if="item.category_id.length > 0" :key="index"
					:to="'/subpages/InquiryInfo/InquiryInfo?id=' + item._id" >
					<!-- 通过header插槽定义列表左侧图片 -->
					<template v-slot:header>
						<!-- 如帖子有图片，以第一张图片作为列表左侧图片；如没有图片，调用占位图 -->
						<image class="avatar" mode="aspectFill"
							:src="!!item.imgs[0] ? item.imgs[0].url : imgPlaceholder" />
					</template>
					<!-- 通过body插槽定义布局 -->
					<template v-slot:body>
						<view class="main">
							<text class="title">{{item.title}}</text>
							<view class="info">
								<!-- 发布人，校园资讯下为author，其他板块下为user_id[0].nickname -->
								<text class="author">
									{{item.user_id[0].nickname ? item.user_id[0].nickname : ''}}
								</text>
								<uni-dateformat class="last_modify_date" :date="item.last_modify_date"
									format="yyyy-MM-dd" :threshold="[60000, 2592000000]" />
							</view>
						</view>
					</template>
				</uni-list-item>
				<!-- 加载状态：上拉加载更多/加载中/没有更多数据了/加载错误 -->
				<!-- #ifdef APP-PLUS -->
				<uni-list-item>
					<template v-slot:body>
						<!-- #endif -->
						<uni-load-state @networkResume="refresh" :state="{data, pagination, hasMore, loading, error}"
							@loadMore="loadMore">
						</uni-load-state>
						<!-- #ifdef APP-PLUS -->
					</template>
				</uni-list-item>
				<!-- #endif -->
			</uni-list>
		</unicloud-db>
	</view>
</template>

<script>
	let cdbRef;
	const db = uniCloud.database();
	/**
	 * 本页展示的帖子类别名
	 */
	const catName = '交友信息';
	export default {
		data() {
			return {
				navBarShow: false,
				showRefresh: false,
				listHight: 0, // 帖子列表高度
				current: 0, // 当前轮播图索引
				/**
				 * 联表列表
				 */
				colList: [
					db.collection('NeuHelper-Posts')
						.field('_id, imgs, title, author, last_modify_date, user_id, category_id').getTemp(),
					db.collection('uni-id-users').field('_id as uid, nickname').getTemp(),
					db.collection('NeuHelper-PostCategories').where(`name == '${catName}'`)
					.field('_id as cid').getTemp()
				],
				/**
				 * 帖子占位图url
				 */
				imgPlaceholder: "https://mp-ba6dadac-aa5f-4abc-a3b4-3abcf3c08fc3.cdn.bspapp.com/cloudstorage/" +
						"2ee411bc-b063-4b84-af7d-8c5f6bc51995.png"
			}
		},
		/** 
		 * 悬停
		 * @param {Object} res
		 */
		onPageScroll(res) {
			if (res.scrollTop > 100) {
				this.navBarShow = true;
			} else {
				this.navBarShow = false;
			}
		},
		async onReady() {
			let t1 = db.collection('NeuHelper-Posts')
				.field('_id, imgs, title, author, last_modifiy_date, user_id, category_id').getTemp();
			let t2 = db.collection('uni-id-users').field('_id, nickname').getTemp();
			let t3 = db.collection('NeuHelper-PostCategories').where(`name == '${catName}'`)
				.field('_id').getTemp();
			
			let t1t2t3 = await db.collection(t1, t2, t3).get();
			console.log("t1t2t3: ", t1t2t3);
		},
		onLoad() {
			// #ifdef APP-NVUE
			/* 可用窗口高度 - 搜索框高 - 状态栏高 */
			this.listHight = uni.getSystemInfoSync().windowHeight - uni.getSystemInfoSync().statusBarHeight - 50 +
				'px';
			// #endif
			// #ifndef APP-NVUE
			this.listHight = 'auto'
			// #endif
			cdbRef = this.$refs.udb
		},
		// async onInit() { //无法在组件渲染前执行，导致catId为空字符串，onDBerror
		// 	// 页面初始化时，查询得出catId
		// 	console.log("const catName: ", catName);
		// 	let catRlt = await db.collection('NeuHelper-PostCategories')
		// 		.where(`name == ${catName}`).field('_id').get();
		// 	console.log("catRlt: ", catRlt);
		// 	catId = "'" + catRlt.result.data[0].name + "'";
		// },
		// 底部下拉事件
		onReachBottom() {
			console.log('课程信息板块-下拉到底啦')
			// 请求新的数据
			this.getNews() //未定义，下拉到底则抛出error
		},
		methods: {
			/**
			 * 轮播图，banner加载后触发的回调，暂未使用
			 */
			onqueryload(data) {},
			changeSwiper(e) {
				this.current = e.detail.current
			},
			//  点击banner的处理
			clickBannerItem(item) {
				// 有外部链接-跳转url
				if (item.open_url) {
					uni.navigateTo({
						url: '/uni_modules/uni-id-pages/pages/common/webview/webview?url=' + item.open_url +
							'&title=' + item.title,
						success: res => {},
						fail: () => {},
						complete: () => {}
					});
				}
				// 其余业务处理
			},
			goHome() {
				uni.switchTab({
					url: '/pages/index/index'
				})
			},
			refresh() {
				cdbRef.loadData({
					clear: true
				}, () => {
					uni.stopPullDownRefresh()
					// #ifdef APP-NVUE
					this.showRefresh = false
					// #endif
					console.log('end');
				})
				console.log('refresh');
			},
			loadMore() {
				cdbRef.loadMore()
			}
		}
	};
</script>

<style lang="scss">
	/* #ifdef APP-NVUE */
	.warp {
		background-color: #fff;
	}

	/* #endif */
	.banner-image {
		width: 750rpx;
		height: 400rpx;
	}

	.swiper-box {
		height: 400rpx;
	}

	/* #ifndef APP-NVUE */
	view {
		display: flex;
		box-sizing: border-box;
		flex-direction: column;
	}

	/* #endif */
	.pages {
		background-color: #FFFFFF;
	}

	.avatar {
		width: 200rpx;
		height: 200rpx;
		margin-right: 10rpx;
	}

	.main {
		justify-content: space-between;
		flex: 1;
	}

	.title {
		font-size: 16px;
	}

	.info {
		flex-direction: row;
		justify-content: space-between;
	}

	.author,
	.last_modify_date {
		font-size: 14px;
		color: #999999;
	}
</style>